#!/usr/bin/perl
use warnings;
use strict;
require 'basic.pl';
my $flag = shift @ARGV;
my $user = shift @ARGV;
if ($flag eq "-l"){
	inc_line($user, 0);
	inc_line($user, 1);
}
elsif ($flag eq "-a"){
	inc_line($user, 1);
}
elsif ($flag eq "-r"){
	inc_line($user, 2);
	echo("users/$user", $ARGV[0]);
	open FH, "users/$user";
	my @ls = <FH>;
	close FH;
	$ls[4] = count_doc($user);
	open OUT, ">", "users/$user";
	print OUT @ls;
	close OUT;
}
elsif ($flag eq "-c"){
	inc_line($user, 3);
}
elsif ($flag eq "-i"){
	system("cat users/template > users/$user");
}
count_doc("user");
sub inc_line {
	my ($user, $line) = @_;
	open IN, "users/$user";
	my @lines = <IN>;
	$lines[$line] = ($lines[$line]+1) . "\n";
	close IN;
	open OUT, ">", "users/$user";
	print OUT @lines;
	close OUT;
}
sub count_doc {
	my $user = $_[0];
	open IN, "users/$user";
	my @lines = <IN>;
	close IN;
	shift @lines;
	shift @lines;
	shift @lines;
	shift @lines;
	shift @lines;
	my %count;
	$count{$_}++ for(@lines);
	my @sorted = sort {$count{$b} <=> $count{$a}} keys %count;
	return $sorted[0];
} 
